package com.itheima.service.impl;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.dao.MemberDao;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.service.MemberService;
import com.itheima.service.ValidateCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

/**
 * 代码使我快乐 Administrator on 2019/12/10.
 */
@Service(interfaceClass = MemberService.class)
@Transactional
public class MemberServiceImpl implements MemberService {

    @Autowired
    private MemberDao memberDao;

    @Autowired
    private ValidateCodeService validateCodeService;

    @Autowired
    private JedisPool jedisPool;

    @Override
    public Member findByTelephone(String telephone) {
        return memberDao.findByTelephone(telephone);
    }

    @Override
    public Result login(String telephone, String validateCode) {

        if (!validateCodeService.validate(telephone,validateCode , RedisMessageConstant.SENDTYPE_LOGIN)) {
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }

        Member member = findByTelephone(telephone);
        if(member == null){
            member = new Member();
            member.setPhoneNumber(telephone);
            member.setRegTime(new Date());

            memberDao.add(member);
        }

        Jedis jedis = jedisPool.getResource();
        String json = JSON.toJSON(member).toString();
        jedis.setex(telephone,60*30 , json);
        jedis.close();
        return new Result(true,MessageConstant.LOGIN_SUCCESS);
    }

    @Override
    public List<Integer> findMemberCountByMonth(List<String> months) {

        List<Integer> list = new ArrayList<>();
        for(String m : months){
                m = m + ".31";//格式：2019.04.31
                Integer count = memberDao.findMemberCountBeforeDate(m);
                list.add(count);
            }
            return list;
        }
}
